package com.zjy.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zjy.basic.constant.WxConstants;
import com.zjy.basic.dto.LoginDto;
import com.zjy.basic.exception.BusinessException;
import com.zjy.basic.jwt.JwtUtils;
import com.zjy.basic.jwt.LoginData;
import com.zjy.basic.jwt.RsaUtils;
import com.zjy.basic.util.AjaxResult;
import com.zjy.basic.util.HttpUtil;
import com.zjy.basic.util.Md5Utils;
import com.zjy.basic.util.StrUtils;
import com.zjy.org.mapper.EmployeeMapper;
import com.zjy.system.domain.Menu;
import com.zjy.user.domain.Logininfo;
import com.zjy.user.domain.User;
import com.zjy.user.domain.Wxuser;
import com.zjy.user.mapper.LogininfoMapper;
import com.zjy.user.mapper.UserMapper;
import com.zjy.user.mapper.WxuserMapper;
import com.zjy.user.service.LogininfoService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        //一.校验：是否空值
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
            throw new BusinessException("信息不能为空!!!");
        }
        //二.校验：账号信息(username+type)是否正确
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);//这里的参数如果是account，就要取消53-56的注释
        if(logininfo == null){
            throw new BusinessException("账号或密码错误!!!");
        }
        //三.校验：密码(密码要加盐加密)
        String inputMd5Pwd  = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if(!inputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误!!!");
        }
        //四.校验：用户是否被禁用
        if(!logininfo.getDisable()){//当状态为false时(禁用的状态)
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }
//        //判断身份是否是0(管理员)
//        if(logininfo.getType()!=0){
//            throw new BusinessException("该账号权限不足");
//        }
        Map<String, Object> map = loginSuccessJWTHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //一.组装第二个请求地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID).replace("SECRET", WxConstants.SECRET).replace("CODE", code);
        //二：使用HttpUtil工具类发送请求,返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //三：将json格式的字符串转成json对象，并获取里面的token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken  = jsonObject.getString("access_token");
        String openid  = jsonObject.getString("openid");
        //四：根据openid去查t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //如果通过openid查询到了wxuser对象
        if(wxuser!=null){//如果不为空，证明该账号绑定过了
            User user = userMapper.findById(wxuser.getUserId());
            if(user != null) {//并且绑定了user对象
                //免密登录
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
                Map<String, Object> map = loginSuccessJWTHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        String params = "?accessToken="+accessToken+"&openid="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        //1.校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验 - 手机验证码校验：是否过期，是否正确 【binder:18566565555 - 9527:1555566666666】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码过期");
        }
        if(!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }
        //3.组装第三个请求地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        //4.通过token和openid发送第三个请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson将json格式的字符串转成json对象，再转成一个Wxuser对象【没有user_id】
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //6.先通过openid去找t_wxuser ,如果有直接删除(特使情况：如果用户的信息在wxuser表有，而user表没了)
        Wxuser dbWxuser = wxuserMapper.findByOpenid(openid);
        if(dbWxuser!=null){
            wxuserMapper.del(dbWxuser.getId());
        }
        //7.想办法创建一个User对象 - 通过phone去创建一个User对象，密码是多少？->搞个随机
        User user = userMapper.findByPhone(phone); //以前是通过手机号码注册，现在又想通过微信绑定登录
        if(user==null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            //8.添加User对象 => 生成一个自增id => 将User_id设置到WxUser对象
            userMapper.add(user);
        }

        //9.添加WxUser对象到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);

        //10.做免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

        Map<String, Object> resultMap = loginSuccessJWTHandler(logininfo);

        return AjaxResult.me().setResultObj(resultMap);
    }

    private Map<String,Object> loginSuccessJWTHandler(Logininfo logininfo){
        //前端不显示密码和盐值（为了安全）
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        //jwt token => 私钥 + LoginData【logininfo + permissions + menus】
        //本来就只需要传递token到前端就可以了，因为token中数据全都有，只需要解密就可以了
        //前端ks代码没有写解密的代码。所以除了将token传递到前端，还需要传递
        //1.logininfo-显示用户信息 2.menus-动态路由-动态菜单 3.permissions-资源权限/按钮权限 4.token-后续发请求要判断是否登录了
        //前台用户没有权限和菜单，前台用户的Map中只有：登录信息logininfo，token
        HashMap<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        if (logininfo.getType()==0){//0表示管理员
            //一：想办法获取当前登录人的权限：permissions - 查那些字段
            List<String> permissions = employeeMapper.getPermissionsByLogininfoId(logininfo.getId());
            //二：想办法获取当前登录人的菜单：menus - 查那些字段
            List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());
            //先把这两个装进map
            map.put("permissions",permissions);
            map.put("menus",menus);
            //三：将permissions，menus，logininfo封装到LoginData中
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
        }

        try {
            //四：通过工具类获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //五：使用工具类和私钥将LoginData加密 => token[jwt token]
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            //六：将permissions，menus，logininfo，token[jwt token]装到Map中响应给前端
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        /*
        "openid":"OPENID",
        "nickname":"NICKNAME",
        "sex":1,
        "province":"PROVINCE",
        "city":"CITY",
        "country":"COUNTRY",
        "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
        "privilege":[
        "PRIVILEGE1",
        "PRIVILEGE2"
        ],
        "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
        * */
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObj.getString("openid"));
        wxuser.setNickname(jsonObj.getString("nickname"));
        wxuser.setHeadimgurl(jsonObj.getString("headimgurl"));
        wxuser.setUnionid(jsonObj.getString("unionid"));
        return wxuser;
    }
}
